package cn.antblog.cos;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

/**
 * COS 对象存储 工具类
 */
public class CosUtils {
    //存储桶名称
    static String emailBucket = "dmc-email-test";

    static String accessKey = "NXTRD373O4Q565WQUEU3";
    static String secretKey = "q3LiWYgCwB9Nuqk1K23Jsw3a77Rnh0mTyDAo3Uwe";
    static String serviceEndpoint = "cos.hhht-hqc.cos.tg.unicom.local";
    static String region = "endpoint hh-prod";
    static AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    static AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider(credentials);
    static ClientConfiguration config = new ClientConfiguration();
    static AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(serviceEndpoint, region);
    static AmazonS3 conn = AmazonS3ClientBuilder.standard()
            .withCredentials(awsStaticCredentialsProvider)
            .withClientConfiguration(config.withProtocol(Protocol.HTTP))
            .withEndpointConfiguration(endpointConfiguration).build();

    /**
     * 获取链接
     *
     * @return
     */
    public static AmazonS3 getConn() {
        return conn;
    }

    /**
     * 获取存储桶名字
     *
     * @param type
     * @return
     */
    public static String getBucketName(String type) {
        String bucketName = emailBucket;
        switch (type) {
            case "email": {
                bucketName = emailBucket;
                break;
            }
            default: {
                break;
            }
        }
        return bucketName;
    }

    /**
     * 上传文件
     *
     * @param localFilePath 本地文件路径
     * @param fileName      上传到COS的文件名称
     * @param type          根据type获取存储桶名称
     * @return
     */
    public static boolean uploadFile(String localFilePath, String fileName, String type) {
        boolean successFlag = false;
        String bucketName = getBucketName(type);
        File file = null;
        FileInputStream is = null;
        try {
            file = new File(localFilePath);
            is = new FileInputStream(file);
            PutObjectResult putObjectResult = conn.putObject(bucketName, fileName, is, new ObjectMetadata());
            successFlag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return successFlag;
    }

    /**
     * 下载文件
     *
     * @param localFilePath 本地文件路径
     * @param fileName      上传到COS的文件名称
     * @param type          根据type获取存储桶名称
     * @return
     */
    public static boolean downloadFile(String localFilePath, String fileName, String type, String... userId) {
//        InitializeUtil.println(fileName+" download start");
        boolean subccessFlag = false;
//        try {
        String bucketName = getBucketName(type);
        conn.getObject(new GetObjectRequest(bucketName, fileName), new File(localFilePath));
        subccessFlag = true;
//            InitializeUtil.println(fileName+" download okok");
//        }catch (Exception e){
//            InitializeUtil.println(fileName+" download not work "+e.getMessage());
//        }
//        InitializeUtil.println(fileName+" download finish");
//        if(localFilePath.indexOf("xlsx")!=-1||localFilePath.indexOf("xls")!=-1){
//            InitializeUtil.println(fileName+" warterMark start");
//            ExcelWaterRemarkUtils.setWaterMarkToExcelByFile(localFilePath,userId[0]);
//            InitializeUtil.println(fileName+" warterMark end");
//        }
        return subccessFlag;
    }

    /**
     * 生成下载链接
     *
     * @param localFilePath 本地文件路径
     * @param fileName      上传到COS的文件名称
     * @param type          根据type获取存储桶名称
     * @return 下载链接
     */
    public static String generateDownloadUrl(String localFilePath, String fileName, String type) {
        URL url = null;
        String bucketName = getBucketName(type);
        boolean successFlag = uploadFile(localFilePath, fileName, type);
        if (successFlag) {
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName);
            url = conn.generatePresignedUrl(request);
        }
        return url == null ? "" : url.toString();
    }


    public static void main(String[] args) {
        downloadFile("D:\\1.xlsx", "daylylz.xlsx", "xlsx");
    }
}
